<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ApiResponseTrait;
use App\Model\CaptchaRecord;
use App\User;
use Gregwar\Captcha\CaptchaBuilder;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class BaseController extends Controller
{
    use ApiResponseTrait;

    protected $error;

    protected function loginUser()
    {
        $loginUser = auth()->user();
        $loginUser = $loginUser?$loginUser:User::find(1);
        return $loginUser;
    }

    protected function isSuper()
    {
        $loginUser = auth()->user();

        return $loginUser?($loginUser->userType=="super"?true:false):false;
    }

    public function captcha()
    {
        $m = new CaptchaBuilder();
        $m->build();
        $code = $m->getPhrase();
        $key  = md5($code);

        $c = new CaptchaRecord();
        $c->key = $key;
        $c->code = $code;
        $c->state  =1;
        $c->save();

        return response()->json(['captcha_key'=>$key,'captcha_img'=>$m->inline()]);
    }

    protected function requestValidate($data,$rules=[],$message=[])
    {
        $validator = Validator::make($data,$rules,$message);
        if ($validator->fails()){
            $this->error = $validator->errors()->first();
            return false;
        }
        return true;
    }
}
